<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="T1Dbmn0YmNZwwxNqq98b7FvVCsxbeIChYP6H75TZjdk">
  <meta name="baidu-site-verification" content="code-86L5xW0tJy">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14.0/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"www.whatsblockchain.com","root":"/","scheme":"Gemini","version":"8.0.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="以太坊中的智能合约使用了一种不常见的存储模型，如果开发者想要对合约中的变量进行寻址，并修改相应的值，那么本文会给予你一些帮助。在接下来篇幅中，我将详细解释以太坊中合约的存储模型，并展示如何使用solidity编程语言使用它。">
<meta property="og:type" content="article">
<meta property="og:title" content="理解以太坊中智能合约中的存储">
<meta property="og:url" content="https://www.whatsblockchain.com/posts/c052872a.html">
<meta property="og:site_name" content="区块链大杂烩">
<meta property="og:description" content="以太坊中的智能合约使用了一种不常见的存储模型，如果开发者想要对合约中的变量进行寻址，并修改相应的值，那么本文会给予你一些帮助。在接下来篇幅中，我将详细解释以太坊中合约的存储模型，并展示如何使用solidity编程语言使用它。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.whatsblockchain.com/assets/2019-04-23/storage.png">
<meta property="og:image" content="https://www.whatsblockchain.com/assets/2019-04-23/fixed.png">
<meta property="og:image" content="https://www.whatsblockchain.com/assets/2019-04-23/dynamic.png">
<meta property="og:image" content="https://www.whatsblockchain.com/assets/2019-04-23/mapping.png">
<meta property="article:published_time" content="2019-04-22T16:00:00.000Z">
<meta property="article:modified_time" content="2020-09-16T06:55:19.917Z">
<meta property="article:author" content="吴寿鹤">
<meta property="article:tag" content="智能合约">
<meta property="article:tag" content="以太坊">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.whatsblockchain.com/assets/2019-04-23/storage.png">


<link rel="canonical" href="https://www.whatsblockchain.com/posts/c052872a.html">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>理解以太坊中智能合约中的存储 | 区块链大杂烩</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-145440251-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-145440251-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9af0452214522472f44968f5a652e2f0";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">区块链大杂烩</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">你想要的这里都有</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
          <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B6%85%E5%A4%A7%E8%8C%83%E5%9B%B4%E7%9A%84%E5%AD%98%E5%82%A8%E7%A9%BA%E9%97%B4"><span class="nav-number">1.</span> <span class="nav-text">超大范围的存储空间</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AF%BB%E6%89%BE%E5%9B%BA%E5%AE%9A%E9%95%BF%E5%BA%A6%E7%9A%84%E5%80%BC"><span class="nav-number">2.</span> <span class="nav-text">寻找固定长度的值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AF%BB%E6%89%BE%E5%8A%A8%E6%80%81%E9%95%BF%E5%BA%A6%E7%9A%84%E5%80%BC"><span class="nav-number">3.</span> <span class="nav-text">寻找动态长度的值</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E9%95%BF%E5%BA%A6%E6%95%B0%E7%BB%84"><span class="nav-number">3.1.</span> <span class="nav-text">动态长度数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Mappings"><span class="nav-number">3.2.</span> <span class="nav-text">Mappings</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%8D%E6%9D%82%E7%B1%BB%E5%9E%8B%E7%9A%84%E7%BB%84%E5%90%88"><span class="nav-number">3.3.</span> <span class="nav-text">复杂类型的组合</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">吴寿鹤</p>
  <div class="site-description" itemprop="description">代码之美，在于架构，架构之美，在于抽象</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">21</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </section>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://www.whatsblockchain.com/posts/c052872a.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="吴寿鹤">
      <meta itemprop="description" content="代码之美，在于架构，架构之美，在于抽象">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="区块链大杂烩">
    </span>

    
    
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          理解以太坊中智能合约中的存储
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-04-23 00:00:00" itemprop="dateCreated datePublished" datetime="2019-04-23T00:00:00+08:00">2019-04-23</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-09-16 14:55:19" itemprop="dateModified" datetime="2020-09-16T14:55:19+08:00">2020-09-16</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6/" itemprop="url" rel="index"><span itemprop="name">智能合约</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
      </div>
      <div class="post-meta">
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>3.8k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>以太坊中的智能合约使用了一种不常见的存储模型，如果开发者想要对合约中的变量进行寻址，并修改相应的值，那么本文会给予你一些帮助。在接下来篇幅中，我将详细解释以太坊中合约的存储模型，并展示如何使用solidity编程语言使用它。</p>
<a id="more"></a>
<h2 id="超大范围的存储空间"><a href="#超大范围的存储空间" class="headerlink" title="超大范围的存储空间"></a>超大范围的存储空间</h2><p>每个运行在以太坊虚拟机（EVM）中的合约会在永久存储空间中（storage）维护一个状态。这个存储空间（storage）是一个非常大的数组，数组长度为$2^{256}$，其中每个元素的大小为32个字节，数组中的每个元素的初始化值为0。任何智能合约都可以从这个存储空间中任何位置读取值，或写入值。</p>
<p><img src="/assets/2019-04-23/storage.png" alt="img"></p>
<p>$2^{256}$长度的存储空间是不能在组成以太坊网络的物理计算机上实现的，实际上的存储空间是非常稀疏的，不需要存储0值，在寻找的时候通过32字节的键映射到32字节的值，这种键值对的方式完成。</p>
<p>因为零不占用任何存储空间，所以我们可以通过将某个值设置为零来回回收存储空间。在智能合约中，当我们将某个变量设置为零时，系统会退还一部分gas给我们。</p>
<h2 id="寻找固定长度的值"><a href="#寻找固定长度的值" class="headerlink" title="寻找固定长度的值"></a>寻找固定长度的值</h2><p>对于已知拥有固定长度的值，通常的方法是在存储空间给他们分配一个预留的位置存储值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">contract StorageTest &#123;</span><br><span class="line">    uint256 a;</span><br><span class="line">    uint256[2] b;</span><br><span class="line"></span><br><span class="line">    struct Entry &#123;</span><br><span class="line">        uint256 id;</span><br><span class="line">        uint256 value;</span><br><span class="line">    &#125;</span><br><span class="line">    Entry c;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于上面的代码：</p>
<ul>
<li><code>a</code>存储在<em>slot</em> 0（在solidity属于中，存储空间中的每一个位置称为“slot”）</li>
<li><code>b</code>存储在<em>slot</em> 1和2中（因为<code>b</code>是一个数组，且数组长度为2）</li>
<li><code>c</code>存储位置从<em>slot</em> 3开始，消耗两个<em>slot</em>，因为<code>Entry</code>结构体存储了两个32字节长度的值</li>
</ul>
<p><img src="/assets/2019-04-23/fixed.png" alt="img"></p>
<p>这些<em>slot</em>位置在合约编译的时候就确定了，并且严格按照变量在合约中的定义顺序确定的。</p>
<h2 id="寻找动态长度的值"><a href="#寻找动态长度的值" class="headerlink" title="寻找动态长度的值"></a>寻找动态长度的值</h2><p>对于固定长度的值使用预分配位置的方法可以很好的解决，但对于这些动态长度的数组和<code>mapping</code>类型的值不起作用，因为无法预先知道到底需要预留多少<code>slot</code>给这些动态类型。</p>
<p>对比我们之前比较熟悉的<code>RAM</code>内存分配方式，你可能会期望有一个”allocation”方法来找到可用空间，然后有一个”free”方法将空间放回到可用的存储池中。</p>
<p>很遗憾这方法并不可行，由于智能合约中的存储空间是天文数字规模的，存储中有$2^{256}$可供选择的位置，这大约是已知可观测宇宙中原子的数目。你可以随机选择存储位置，而不用担心会发生冲突。在solidity中使用hash函数为动态长度的类型值计算存储位置。</p>
<h3 id="动态长度数组"><a href="#动态长度数组" class="headerlink" title="动态长度数组"></a>动态长度数组</h3><p>动态长度的数组需要一个位置来存储数组的长度和数组中的所有元素。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">contract StorageTest &#123;</span><br><span class="line">    uint256 a;     &#x2F;&#x2F; slot 0</span><br><span class="line">    uint256[2] b;  &#x2F;&#x2F; slots 1-2</span><br><span class="line"></span><br><span class="line">    struct Entry &#123;</span><br><span class="line">        uint256 id;</span><br><span class="line">        uint256 value;</span><br><span class="line">    &#125;</span><br><span class="line">    Entry c;       &#x2F;&#x2F; slots 3-4</span><br><span class="line">    Entry[] d;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于上面的代码：</p>
<ul>
<li>动态数组<code>d</code>存储在<em>slot</em> 5位置中，但<em>slot</em> 5中存储的值是数组<code>d</code>的长度，数组中的元素连续存储在以<code>hash(5)</code>开始的位置中。即通过对动态数组<code>d</code>的<code>slot</code>进行hash运算，求出数组中的元素存储位置。</li>
</ul>
<p><img src="/assets/2019-04-23/dynamic.png" alt="img"></p>
<p>下面一段<code>solidity</code>代码用来计算动态数组中元素的位置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function arrLocation(uint256 slot, uint256 index, uint256 elementSize)</span><br><span class="line">    public</span><br><span class="line">    pure</span><br><span class="line">    returns (uint256)</span><br><span class="line">&#123;</span><br><span class="line">    return uint256(keccak256(slot)) + (index * elementSize);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Mappings"><a href="#Mappings" class="headerlink" title="Mappings"></a>Mappings</h3><p>映射需要找到与给定键对应的位置的有效方法。散列键是一个好的开始，但是必须注意确保不同的映射生成不同的位置。</p>
<p><code>mapping</code>需要一个有效的方法通过给定的key找到相应的存储位置，通过对<code>mapping</code>的key进行hash运算是一个不错的方法，但需要确保针对不同的<code>mapping</code>对象的相同的<code>key</code>生成不同的存储位置。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">contract StorageTest &#123;</span><br><span class="line">    uint256 a;     &#x2F;&#x2F; slot 0</span><br><span class="line">    uint256[2] b;  &#x2F;&#x2F; slots 1-2</span><br><span class="line"></span><br><span class="line">    struct Entry &#123;</span><br><span class="line">        uint256 id;</span><br><span class="line">        uint256 value;</span><br><span class="line">    &#125;</span><br><span class="line">    Entry c;       &#x2F;&#x2F; slots 3-4</span><br><span class="line">    Entry[] d;     &#x2F;&#x2F; slot 5 for length, keccak256(5)+ for data</span><br><span class="line"></span><br><span class="line">    mapping(uint256 &#x3D;&gt; uint256) e;</span><br><span class="line">    mapping(uint256 &#x3D;&gt; uint256) f;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于以上代码：</p>
<ul>
<li><code>e</code>的<em>slot</em>是6，<code>f</code>的<em>slot</em>是7，但在这两个位置中并没有存储任何值，因为<code>mapping</code>没有长度值需要存储</li>
</ul>
<p>要寻找<code>mapping</code>中的值的位置，需要将<code>key</code>与<code>mapping</code>的<em>slot</em>一起进行hash运算。</p>
<p><img src="/assets/2019-04-23/mapping.png" alt="img"></p>
<p>下面的<code>solidity</code>函数用于计算<code>mapping</code>中值的存储位置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function mapLocation(uint256 slot, uint256 key) public pure returns (uint256) &#123;</span><br><span class="line">    return uint256(keccak256(key, slot));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意：当传入多个参数到<code>keccak256</code>方法时，首先会将这些参数进行连接，然后在进行hash运算。因为是将<code>mapping</code>的slot值与<code>key</code>值同时进行的hash运算，所以不同<code>mapping</code>之间是不会存在冲突的。</p>
<h3 id="复杂类型的组合"><a href="#复杂类型的组合" class="headerlink" title="复杂类型的组合"></a>复杂类型的组合</h3><p>动态大小的数组与<code>mapping</code>可以相互嵌套在一起，当这种情况发生时，可以通过递归的方式找到值的存储位置。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">contract StorageTest &#123;</span><br><span class="line">    uint256 a;     &#x2F;&#x2F; slot 0</span><br><span class="line">    uint256[2] b;  &#x2F;&#x2F; slots 1-2</span><br><span class="line"></span><br><span class="line">    struct Entry &#123;</span><br><span class="line">        uint256 id;</span><br><span class="line">        uint256 value;</span><br><span class="line">    &#125;</span><br><span class="line">    Entry c;       &#x2F;&#x2F; slots 3-4</span><br><span class="line">    Entry[] d;     &#x2F;&#x2F; slot 5 for length, keccak256(5)+ for data</span><br><span class="line"></span><br><span class="line">    mapping(uint256 &#x3D;&gt; uint256) e;    &#x2F;&#x2F; slot 6, data at h(k . 6)</span><br><span class="line">    mapping(uint256 &#x3D;&gt; uint256) f;    &#x2F;&#x2F; slot 7, data at h(k . 7)</span><br><span class="line"></span><br><span class="line">    mapping(uint256 &#x3D;&gt; uint256[]) g;  &#x2F;&#x2F; slot 8</span><br><span class="line">    mapping(uint256 &#x3D;&gt; uint256)[] h;  &#x2F;&#x2F; slot 9</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>要寻找这些复杂类型中的值的存储位置可以使用上面定义的函数：</p>
<ul>
<li>arrLocation</li>
<li>mapLocation</li>
</ul>
<p>例：寻找<code>g[123][0]</code>的存储位置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 首先找到g[123]的位置，g是mapping，g的slot是8，key是123，用mapLocation计算存储位置</span><br><span class="line">arrLoc &#x3D; mapLocation(8, 123);  &#x2F;&#x2F; g is at slot 8</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 然后 查找arr[0]</span><br><span class="line">itemLoc &#x3D; arrLocation(arrLoc, 0, 1);</span><br></pre></td></tr></table></figure>
<p>例：寻找 <code>h[2][456]</code>的存储位置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 首先查找h[2]位置，h是动态数组，h的slot是9</span><br><span class="line">mapLoc &#x3D; arrLocation(9, 2, 1);  &#x2F;&#x2F; h is at slot 9</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 然后查找 map[456]位置</span><br><span class="line">itemLoc &#x3D; mapLocation(mapLoc, 456);</span><br></pre></td></tr></table></figure>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><ul>
<li>每个智能合约中的<code>storage</code>都是以$2^{256}$长度的数组形式存在的，并且数组中的所有元素的初始值为0</li>
<li>0值是不会被显示存储的，所以当给一个对象赋值0时，就相当于生命回收相应的存储空间</li>
<li>对与固定长度的值，solidity是通过预分配的方式分配存储位置的</li>
<li>对于动态长度类型的值，Solidity通过hash运算的方法动态确定存储位置</li>
</ul>
<p>下表展示了如何计算不同类型的存储位置。<code>slot</code>表示在合约中定义的变量的位置。</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>Kind</th>
<th>Declaration</th>
<th>Value</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>一般类型</td>
<td><code>T v</code></td>
<td><code>v</code></td>
<td>v’s slot</td>
</tr>
<tr>
<td>定长数组</td>
<td><code>T[10] v</code></td>
<td><code>v[n]</code></td>
<td>(v’s slot) + n * (size of T)</td>
</tr>
<tr>
<td>不定长数组</td>
<td><code>T[] v</code></td>
<td><code>v[n]</code></td>
<td>keccak256(v’s slot) + n * (size of T)</td>
</tr>
<tr>
<td></td>
<td></td>
<td><code>v.length</code></td>
<td>v’s slot</td>
</tr>
<tr>
<td>Mapping</td>
<td><code>mapping(T1 =&gt; T2) v</code></td>
<td><code>v[key]</code></td>
<td>keccak256(key . (v’s slot))</td>
</tr>
</tbody>
</table>
</div>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/posts/7664e5f1.html" rel="bookmark">暂停交易？ERC20合约整数溢出安全漏洞案例技术分析（一）</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/posts/3e17fcd9.html" rel="bookmark">科普：什么是以太坊</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/posts/318c223a.html" rel="bookmark">zkRollup介绍 原理篇 </a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/posts/58cf1c1b.html" rel="bookmark">零知识证明介绍 </a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/posts/2e1e9deb.html" rel="bookmark">精通 Uniswap</a></div>
    </li>
  </ul>


    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>原作者： </strong>吴寿鹤
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://www.whatsblockchain.com/posts/c052872a.html" title="理解以太坊中智能合约中的存储">https://www.whatsblockchain.com/posts/c052872a.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6/" rel="tag"># 智能合约</a>
              <a href="/tags/%E4%BB%A5%E5%A4%AA%E5%9D%8A/" rel="tag"># 以太坊</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/126665fc.html" rel="prev" title="IPOS共识算法设计">
                  <i class="fa fa-chevron-left"></i> IPOS共识算法设计
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/bdff6814.html" rel="next" title="从软件分层开发角度理解tendermint">
                  从软件分层开发角度理解tendermint <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
  
  
  



      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">吴寿鹤</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">87k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:19</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.0/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


















  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  
      <script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              const target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    const script = document.createElement('script');
    script.src = '//cdn.jsdelivr.net/npm/mathjax@3.1.0/es5/tex-mml-chtml.js';
    script.defer = true;
    document.head.appendChild(script);
  } else {
    MathJax.startup.document.state(0);
    MathJax.typesetClear();
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  

</body>
</html>
